import {_decorator, Animation, Component} from 'cc';
import {GameManager} from "db://assets/scripts/game/GameManager";
import {UIManager} from "db://assets/scripts/common/UIManager";
import {EventManager} from "db://assets/scripts/common/EventManager";
import {EventType} from "db://assets/scripts/common/EventType";

const {ccclass, property} = _decorator;

/**
 * 加载界面控制器
 */
@ccclass('LoadingController')
export class LoadingController extends Component {
    /**
     * 动画
     */
    @property(Animation)
    public cloudAnimation: Animation;

    /**
     * 是否展示结束
     */
    private isShowOver: boolean = false;
    /**
     * 是否需要隐藏
     */
    private isNeedHide: boolean = false;
    /**
     * 展示时的回调
     */
    private showCallback: Function;
    /**
     * 隐藏时的回调
     */
    private hideCallback: Function;

    onEnable() {
        EventManager.on(EventType.HIDE_LOADING_PANEL, this.hideLoading, this);
    }

    onDisable() {
        EventManager.off(EventType.HIDE_LOADING_PANEL, this.hideLoading, this);
    }

    /**
     * 显示正在加载界面
     *
     * @param callback 显示时的回调
     */
    public show(callback?: Function) {
        this.isShowOver = false;
        this.isNeedHide = false;
        this.showCallback = callback;

        this.showLoading();
    }

    /**
     * 隐藏加载动画
     *
     * @param callback 隐藏时的回调
     */
    private hideLoading(callback?: Function) {
        this.hideCallback = callback;
        this.isNeedHide = true;
        if (this.isShowOver) {
            GameManager.getInstance().gameCameraController.resetCamera();

            this.hideCallback && this.hideCallback();
            this.cloudAnimation.getState("cloudAnimationOut").time = 0;
            this.cloudAnimation.getState("cloudAnimationOut").sample();
            this.cloudAnimation.play("cloudAnimationOut");
            this.cloudAnimation.once(Animation.EventType.FINISHED, () => {
                UIManager.getInstance().hideDialog("loading/loadingPanel");
                UIManager.getInstance().showDialog("fight/fightPanel", [this]);
            });
        }
    }

    /**
     * 显示加载动画
     */
    private showLoading() {
        this.cloudAnimation.getState("cloudAnimationIn").time = 0;
        this.cloudAnimation.getState("cloudAnimationIn").sample();
        this.cloudAnimation.play("cloudAnimationIn");
        this.cloudAnimation.once(Animation.EventType.FINISHED, () => {
            this.showCallback && this.showCallback();

            this.isShowOver = true;

            if (this.isNeedHide) {
                this.hideLoading(this.hideCallback);
            }
        });
    }
}